class_name DraggingAndHighlightTile
extends TileHighlighter
## 版本：1.0.0
## 功能：拖拽 Unit 时高亮游戏性区域
## 使用：挂载到 Node 节点上，配置 play_areas 导出变量。

#region Exported parameters
## 可以被高亮的游戏性区域
@export var play_areas: Array[PlayArea]
#endregion


func setup_unit(unit: Unit) -> void:
	unit.drag_and_drop.drag_started.connect(_on_unit_drag_started)
	unit.drag_and_drop.drag_canceled.connect(_on_unit_drag_canceled.unbind(1))
	unit.drag_and_drop.dropped.connect(_on_unit_dropped.unbind(1))


func _process(_delta: float) -> void:
	if not enabled or play_areas.size() == 0:
		return
	
	var mouse_global_position := play_areas[0].get_global_mouse_position()
	
	var mouse_hovered_play_area := _get_play_area_from_world_global_position(mouse_global_position)
	if mouse_hovered_play_area:
		clear_highlighted_tiles()
		highlight_tile_from_world_global_position(mouse_global_position)

	_update_tiles()


func _get_play_area_from_world_global_position(world_global_position: Vector2) -> PlayArea:
	for play_area in play_areas:
		var cell_position := play_area.get_cell_position_from_world_global_position(world_global_position)
		if play_area.unit_grid.is_cell_in_grid(cell_position):
			return play_area
	return null


func _on_unit_drag_started() -> void:
	enabled = true


func _on_unit_drag_canceled() -> void:
	enabled = false


func _on_unit_dropped() -> void:
	enabled = false
